import streamlit as st
from langserve import RemoteRunnable
from patagent.constant import CONFLUENCE_PAGEIDS, HISTORY_LEN

qa_agent = RemoteRunnable("http://192.168.3.89:1888/rag/")
response = ''

def get_question_with_history():
    history = ''
    for message in st.session_state.messages[-HISTORY_LEN:]:
        history += message['role'] + ': ' + message['content'] + '\n'
    return history

def stream_call():
    """Need deploy to LangGraph Cloud Flatform"""

st.title("Patent 助手")
st.markdown(f"**已开启对话记忆，可记忆:red[{HISTORY_LEN}]轮对话**")
st.success('已载入 Confluence PageIds: ' + str(CONFLUENCE_PAGEIDS))
st.success("已载入 business-openapi APIs")

# Initialize chat history
if "messages" not in st.session_state:
    st.session_state.messages = []

# Display chat messages from history on app rerun
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

# Accept user input
if question := st.chat_input("input your question"):
    # Display user message in chat message container
    with st.chat_message("user"):
        st.markdown(question)
    # Add user message to chat history
    st.session_state.messages.append({"role": "user", "content": question})

    # Display assistant response in chat message container
    with st.chat_message("assistant"):
        response = qa_agent.invoke(get_question_with_history())
        st.markdown(response)
    # Add assistant response to chat history
    st.session_state.messages.append({"role": "assistant", "content": response})